import { Node, UITransform, Layers, SpriteFrame } from 'cc'

// 创建UI组件并设置基础属性
export const createUINode = (name: string = '') => {
  const node = new Node(name)
  // 添加UI组件
  const transform = node.addComponent(UITransform)
  //设置原点
  transform.setAnchorPoint(0, 1)
  //设置layer
  node.layer = 1 << Layers.nameToLayer('UI_2D')
  return node
}

// 生成区间随机数
export const randomByRange = (start: number, end: number): number => {
  return start + Math.floor((end - start) * Math.random())
}
const getNumberWithString = (str: string) => parseInt(str.match(/\((\d+)\)/)[1] || '0')

// 文件排序
export const sortSpriteFrame = (spriteFrames: Array<SpriteFrame>) =>
  spriteFrames.sort((a, b) => getNumberWithString(a.name) - getNumberWithString(b.name))

export const randomString = (length: number): string => {
  const str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let result = ''
  for (let i = length; i > 0; --i) result += str[Math.floor(Math.random() * str.length)]
  return result
}
